//
//  WZTaskManagerController.m
//  WZEfengAndEtong
//
//  Created by wanzhao on 16/6/8.
//  Copyright © 2016年 wanzhao. All rights reserved.
//

#import "WZTaskManagerController.h"
#import "WZTaskManagerCell.h"
#import "WZTask.h"
#import "WZDetailTaskController.h"
#import "WZTaskButton.h"
#import "WZTaskLogController.h"
#import "WZFinished.h"
#import "WZAcceptController.h"
#import "WZDoingController.h"
#import "CFolderMgr.h"
#import "CContactMgr.h"
#import "CContactModel.h"
#import "CAccountModel.h"
#import "WZCheckController.h"
#import "WZTaskNoAvailableCell.h"

@interface WZTaskManagerController ()

@property (nonatomic, strong) CContactModel *curAccount;
@property (nonatomic, strong) CAccountModel *acc;

/**任务模型数组*/
@property (nonatomic, strong) NSMutableArray *taskArray;

@property (nonatomic, assign) NSInteger count;

// 记录收缩状态  对应的把每个区的展开收缩记录下来
@property (strong, nonatomic) NSMutableDictionary *dataDic;

@property (nonatomic, strong) WZTaskButton   *taskBtn;
/**已完成任务*/
@property (nonatomic, strong) NSMutableArray *finishedTask;
/**任务组*/
@property (nonatomic, strong) NSArray  *taskGroups;
/**OA用户名*/
@property (nonatomic, copy  ) NSString *oaUserName;
/**OA 登陆密码*/
@property (nonatomic, copy  ) NSString *oaPwd;
/**OA userId*/
@property (nonatomic, copy  ) NSString *oaUserId;
/**OA 公司ID*/
@property (nonatomic, copy  ) NSString *oaCompanyID;
/**OA Name*/
@property (nonatomic, copy  ) NSString *oaName;

@property (nonatomic, assign) BOOL flag;

@end

@implementation WZTaskManagerController

static NSString *const taskCellID = @"taskCellID";
static NSString *const NO_Available_CellID = @"NO_Available_CellID";

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupTableView];
    
    // 获取任务列表
    [self getTaskList];
    
    [self getTaskList2];
    
//    [self loadTaskData];

}


- (void)setupTableView {
    
    
    self.tableView = [[UITableView alloc] initWithFrame:[UIScreen mainScreen].bounds style:UITableViewStyleGrouped];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.rowHeight = 50;
    self.tableView.tableFooterView = [[UIView alloc] init];
    self.tableView.backgroundColor = WZRGBColor(246, 245, 250);
    
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([WZTaskManagerCell class]) bundle:nil] forCellReuseIdentifier:taskCellID];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([WZTaskNoAvailableCell class]) bundle:nil] forCellReuseIdentifier:NO_Available_CellID];
    
    self.title = @"任务管理";
    
    self.dataDic = [@{@"0":@"0",
                      @"1":@"1"}
                    mutableCopy];
    
    self.taskGroups = [NSMutableArray arrayWithObjects:self.taskArray, self.finshedTask, nil];
    self.count = 0;
    self.flag = YES;
    
//    CAccountModel *acc = [[CFolderMgr shareInstance].accMgr getRecentlyLoginAccount];
//    self.acc = acc;
//    self.curAccount = [[[CContactMgr alloc] init] loadContactWithUserCode:acc.userName];
    
    // 获取OA账户信息
    self.oaUserName = [[USER_DEFAULT objectForKey:@"oaUserName"] stringByReplacingOccurrencesOfString:@"@" withString:@"_"];
    self.oaUserId = [USER_DEFAULT objectForKey:@"oaUserId"];
    self.oaPwd = [[USER_DEFAULT objectForKey:@"oaPwd"] md5String];
    self.oaCompanyID = [USER_DEFAULT objectForKey:@"oaCompanyID"];
    self.oaName = [USER_DEFAULT objectForKey:@"oaName"];
}


/**加载任务数据*/
- (void)loadTaskData {
    
    [NetWorkShare getTaskStatusWithName:self.oaUserName pwd:self.oaPwd SuccessHandle:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        if (responseObject) {
            if ([[responseObject objectForKey:@"success"] boolValue]) {
                
                WZLog(@"%@", responseObject);
            } else {
                
                [MBProgressHUD showMessage:@"message"];
            }
        } else {
            
            [MBProgressHUD showMessage:UNKNOWNERROR];
        }
        
    } FailureHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
        [MBProgressHUD showError:NETWORKNERROR];
        WZLog(@"错误 = %@", error);
    }];
}


/**获取任务列表*/
- (void)getTaskList {
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"name"] = self.oaUserName;
    params[@"pwd"] = self.oaPwd;
    params[@"page"] = @"1"; // 当前页
    params[@"rows"] = @"20"; //每页数量
    params[@"taskName"] = @" "; // 查询全部是null
    params[@"isFinish"] = @"0"; // 2 全部, 0 未完成
    params[@"status"] = @"0"; // 全部
    params[@"assignType"] = @"0";
    
    [NetWorkShare getTaskListWithParams:params SuccessHandle:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (responseObject) {
            
            if ([[responseObject objectForKey:@"success"] boolValue]) {
                
                // 遍历字典数组
                [self.taskArray removeAllObjects];
                self.taskArray = [WZTask objectArrayWithKeyValuesArray:responseObject[@"rows"]];
                
                [self.taskArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    
                    
                }];
                
                if (self.tableView.window) [self.tableView reloadData];
                
            } else {
                
                [MBProgressHUD showError:[responseObject objectForKey:@"message"]];
            }
        } else {
            
            [MBProgressHUD showError:UNKNOWNERROR];
        }
    } FailureHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
        [MBProgressHUD hideHUD];
        [MBProgressHUD showError:NETWORKNERROR];
        WZLog(@"error = %@", error);
    }];
}


- (void)getTaskList2 {
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"name"] = self.oaUserName;
    params[@"pwd"] = self.oaPwd;
    params[@"page"] = @"1"; // 当前页
    params[@"rows"] = @"20"; //每页数量
    params[@"taskName"] = @" "; // 查询全部是null
    params[@"isFinish"] = @"1"; // 2 全部, 1 完成
    params[@"status"] = @"0"; // 全部
    params[@"assignType"] = @"0";
    
    [NetWorkShare getTaskListWithParams:params SuccessHandle:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (responseObject) {
            
            if ([[responseObject objectForKey:@"success"] boolValue]) {
                
                self.finishedTask = [WZFinished objectArrayWithKeyValuesArray:responseObject[@"rows"]];
                
                [self.tableView reloadData];
                
            } else {
                [MBProgressHUD showError:[responseObject objectForKey:@"message"]];
            }
        } else {
            
            [MBProgressHUD showError:UNKNOWNERROR];
        }
    } FailureHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
        [MBProgressHUD showError:NETWORKNERROR];
        WZLog(@"error = %@", error);
    }];
}


#pragma mark -- set navgationBar

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
    if (!IsIOS7) {
        self.navigationController.navigationBar.tintColor = RGBCOLOR(94, 196, 206);
    } else {
        
        self.navigationController.navigationBar.barTintColor = RGBCOLOR(94, 196, 206);
    }
} 

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
   
    return self.taskGroups.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
//    if ([[self.dataDic valueForKey:[NSString stringWithFormat:@"%ld", section]] isEqualToString:@"0"]) {
//        
//        return self.taskArray.count;
//    
//    } else {
//        
//        return self.finshedTask.count;
//    }
    
//    return self.taskArray.count;
    
    if (0 == section) {
        
        if (!self.taskArray.count) {
            return 1;
        } else {
            return self.taskArray.count;
        }
        
    } else {
        
        return self.count;
    }
    
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (0 == indexPath.section) {
        if (self.taskArray.count) {
            WZTaskManagerCell *cell = [tableView dequeueReusableCellWithIdentifier:taskCellID];
            cell.oaUserId = self.oaUserId;
            cell.taskList =  self.taskArray[indexPath.row];
            return cell;
        } else {
            WZTaskNoAvailableCell *cell = [tableView dequeueReusableCellWithIdentifier:NO_Available_CellID];
            cell.userInteractionEnabled = NO;
            cell.textLabel.textAlignment = NSTextAlignmentCenter;
            cell.textLabel.font = [UIFont systemFontOfSize:14];
            cell.textLabel.text = @"没有任务";
            return cell;
        }
    }

    if (1 == indexPath.section) {
        
        WZTaskManagerCell *cell = [tableView dequeueReusableCellWithIdentifier:taskCellID];
        cell.oaUserId = self.oaUserId;
        cell.finshed = self.finshedTask[indexPath.row];
        return cell;
    }
    
    return nil;
}

#pragma mark -- 点击cell 的代理方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (1 == indexPath.section) {
        
        WZFinished *finishedTask = self.finishedTask[indexPath.row];
        
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"WZDoing" bundle:nil];
        WZDoingController *doingVC = [storyboard instantiateViewControllerWithIdentifier:@"doingTask"];
        doingVC.taskId = finishedTask.taskID;
        doingVC.oaUserName = self.oaUserName;
        doingVC.oaPwd = self.oaPwd;
        doingVC.oaName = self.oaName;
        doingVC.oaUserId = self.oaUserId;
        doingVC.block = ^(){
            [self getTaskList];
            [self getTaskList2];
        };
        [self.navigationController pushViewController:doingVC animated:YES];
        
    } else if (0 == indexPath.section) {
        
         WZTask *task = self.taskArray[indexPath.row];
    
        if ([task.status isEqualToNumber:@(1)]) {//待接受的
            
            UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"WZAccept" bundle:nil];
            WZAcceptController *acceptVc = [storyboard instantiateViewControllerWithIdentifier:@"acceptTask"];
            acceptVc.taskId = task.taskID;
            acceptVc.oaUserName = self.oaUserName;
            acceptVc.oaPwd = self.oaPwd;
            acceptVc.oaName = self.oaName;
            acceptVc.oaUserId = self.oaUserId;
            acceptVc.assignerId = task.assignerId;
            acceptVc.executorId = task.executorId;
            
            [self.navigationController pushViewController:acceptVc animated:YES];
            
        } else if ([task.status isEqualToNumber:@(2)]) {//被拒绝的
            
            UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"WZDetailTask" bundle:nil];
            WZDetailTaskController *refuseVC = [storyboard instantiateViewControllerWithIdentifier:@"detailTask"];
            refuseVC.taskId = task.taskID;
            refuseVC.oaUserName = self.oaUserName;
            refuseVC.oaPwd = self.oaPwd;
            refuseVC.oaName = self.oaName;
            refuseVC.oaUserId = self.oaUserId;
            
            [self.navigationController pushViewController:refuseVC animated:YES];
            
            WZLog(@"被拒绝");
            
        } else if ([task.status isEqualToNumber:@(3)]) {// 未开始
            
            WZLog(@"未开始的");
            
            UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"WZDoing" bundle:nil];
            WZDoingController *doingVC = [storyboard instantiateViewControllerWithIdentifier:@"doingTask"];
            doingVC.taskId = task.taskID;
            doingVC.oaUserName = self.oaUserName;
            doingVC.oaPwd = self.oaPwd;
            doingVC.oaName = self.oaName;
            doingVC.oaUserId = self.oaUserId;
            
            [self.navigationController pushViewController:doingVC animated:YES];

            
        } else if ([task.status isEqualToNumber:@(4)]) { // 实施中
            
            UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"WZDoing" bundle:nil];
            WZDoingController *doingVC = [storyboard instantiateViewControllerWithIdentifier:@"doingTask"];
            doingVC.taskId = task.taskID;
            doingVC.oaUserName = self.oaUserName;
            doingVC.oaPwd = self.oaPwd;
            doingVC.oaName = self.oaName;
            doingVC.oaUserId = self.oaUserId;
            
            [self.navigationController pushViewController:doingVC animated:YES];
            
        } else if ([task.status isEqualToNumber:@(7)]) { // 待审核
            
            // 知会我的
            if (![self.oaUserId isEqualToString:task.executorId] && ![self.oaUserId isEqualToString:task.assignerId]) {
                
                UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"WZDoing" bundle:nil];
                WZDoingController *doingVC = [storyboard instantiateViewControllerWithIdentifier:@"doingTask"];
                doingVC.taskId = task.taskID;
                doingVC.oaUserName = self.oaUserName;
                doingVC.oaPwd = self.oaPwd;
                doingVC.oaName = self.oaName;
                doingVC.oaUserId = self.oaUserId;
                
                [self.navigationController pushViewController:doingVC animated:YES];
                
                // 我是分配人不是执行者
            } else if ([self.oaUserId isEqualToString:task.assignerId] && ![self.oaUserId isEqualToString:task.executorId]) {
                
                UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"WZCheck" bundle:nil];
                WZCheckController *checkVc = [storyboard instantiateViewControllerWithIdentifier:@"checkTask"];
                checkVc.taskId = task.taskID;
                checkVc.oaUserName = self.oaUserName;
                checkVc.oaPwd = self.oaPwd;
                checkVc.oaName = self.oaName;
                checkVc.oaUserId = self.oaUserId;
                checkVc.assignerId = task.assignerId;
                checkVc.executorId = task.executorId;
                
                [self.navigationController pushViewController:checkVc animated:YES];
                
                // 我是执行者不是分配者
            } else if (![self.oaUserId isEqualToString:task.assignerId] && [self.oaUserId isEqualToString:task.executorId]) {
                
                UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"WZDoing" bundle:nil];
                WZDoingController *doingVC = [storyboard instantiateViewControllerWithIdentifier:@"doingTask"];
                doingVC.taskId = task.taskID;
                doingVC.oaUserName = self.oaUserName;
                doingVC.oaPwd = self.oaPwd;
                doingVC.oaName = self.oaName;
                doingVC.oaUserId = self.oaUserId;
                
                [self.navigationController pushViewController:doingVC animated:YES];
                
                // 执行和分配是同一个人
            } else if ([self.oaUserId isEqualToString:task.assignerId] && [self.oaUserId isEqualToString:task.executorId]) {
                
                UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"WZDoing" bundle:nil];
                WZDoingController *doingVC = [storyboard instantiateViewControllerWithIdentifier:@"doingTask"];
                doingVC.taskId = task.taskID;
                doingVC.oaUserName = self.oaUserName;
                doingVC.oaPwd = self.oaPwd;
                doingVC.oaName = self.oaName;
                doingVC.oaUserId = self.oaUserId;
                
                [self.navigationController pushViewController:doingVC animated:YES];
                
            }
            
        } else {
            
            [MBProgressHUD showError:@"已终止或者已完成的任务!"];
            WZLog(@"已终止或者已完成的任务!");
        }
        
    } else {
        
        WZLog(@"====");
    }
    
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    
    if (0 == section) {
        
        return nil;
    } else {
        
        return @"显示已完成的任务";
    }
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    if (0 == section) {
        return 0.01;
        
    } else {
        
        return 30;
    }
    
//    return 30;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    if (0 == section) {
        return nil;
    }
    
    WZTaskButton *taskBtn = [WZTaskButton buttonWithType:UIButtonTypeCustom];
    self.taskBtn = taskBtn;
    
    if (self.flag == YES) {
        
        [taskBtn setTitle:@"显示已完成任务" forState:UIControlStateNormal];
        
    } else {
        
        [taskBtn setTitle:@"隐藏已完成任务" forState:UIControlStateNormal];
    }
    

    taskBtn.titleLabel.font = Font14;
    [taskBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    [taskBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateSelected];
//    [taskBtn adjustsImageWhenHighlighted];
    taskBtn.frame = CGRectMake(0, 0, 0, 30);
    [taskBtn addTarget:self action:@selector(taskBtnDidClick:) forControlEvents:UIControlEventTouchUpInside];
    
    taskBtn.tag = section + 3000;
    
    return taskBtn;
}

- (void)taskBtnDidClick:(UIButton *)sender{
//    self.taskBtn.selected = !self.taskBtn.selected;
//    NSInteger temp = sender.tag - 3000;
    
    if (!self.flag) {
        self.flag = 1;
        self.count = 0;
        [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationBottom];
        
    } else {
        
        self.flag = 0;
        self.count = self.finishedTask.count;
        [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationAutomatic];
        
//        [self.tableView setContentOffset:CGPointMake(CGFLOAT_MAX, CGFLOAT_MAX)];
        
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.count - 1 inSection:1];
        
        [self TableView:self.tableView scrollToBottomAtIndexpath:indexPath Animated:YES];
    }
    
    
//    if ([[self.dataDic valueForKey:[NSString stringWithFormat:@"%ld", temp]] isEqualToString:@"0"]) {
//    
//        [self.dataDic setObject:@"1" forKey:[NSString stringWithFormat:@"%ld", temp]];
//        
////        [sender setTitle:@"隐藏已完成任务" forState:UIControlStateNormal];
//    } else {
//        
//        [self.dataDic setObject:@"0" forKey:[NSString stringWithFormat:@"%ld", temp]];
//
//    }
//    
//    [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:temp] withRowAnimation:UITableViewRowAnimationAutomatic];
    
}

- (NSMutableDictionary *)dataDic {
    
    if (_dataDic == nil) {
        _dataDic = [[NSMutableDictionary alloc] init];
    }
    return _dataDic;
}

- (NSMutableArray *)taskArray {
    
    if (_taskArray == nil) {
        _taskArray = [[NSMutableArray alloc] init];
    }
    return _taskArray;
}


- (NSMutableArray *)finshedTask {
    
    if (_finishedTask == nil) {
        _finishedTask = [[NSMutableArray alloc] init];
    }
    return _finishedTask;
}

- (void)TableView:(UITableView *)tableView scrollToBottomAtIndexpath:(NSIndexPath *)indexPath Animated:(BOOL)animation {
    
    // 多少组
    NSInteger sections = [tableView numberOfSections];
    
    if (sections < 1) return;
    
    // 最后一组有多少行
    NSInteger rows = [tableView numberOfRowsInSection:sections - 1];
    
    if (rows < 1) return;
    
//    NSIndexPath *indexpath = [NSIndexPath indexPathForRow:rows - 1 inSection:sections - 1];
    
    [tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}
@end
